package thread_order_print;

import java.util.LinkedHashMap;
import java.util.Map;

public class PrintQueue {
    public int targetNum = 0;    //要打印的目标数量
    public int printOnce = 0;    //一次要打印的次数
    private int nowNum = 1;        //目前打印到的数量

    /**
     * @param targetNum 要打印的目标数量
     * @param printOnce 一次要打印的次数
     */
    public PrintQueue(int targetNum, int printOnce) {
        this.targetNum = targetNum;
        this.printOnce = printOnce;
    }

    private int nextThreadNum = 0;//下次要执行线程的下标
    private int threadCount = 0;//总的线程数量

    //map集合，存放线程，键是具体线程，值存放线程打印的顺序
    private Map<Thread, Integer> threads = new LinkedHashMap<Thread, Integer>();

    //添加线程
    public void setThread(Thread thread) {
        threads.put(thread, threadCount);
        threadCount++;
    }

    //运行线程
    public void run() {
        for (Thread thread : threads.keySet()) {
            thread.start();
        }
    }

    public synchronized void printNum() throws InterruptedException {
        //获取当前线程
        Thread currentThread = Thread.currentThread();
        //获取当前线程坐标
        int currentNum = threads.get(currentThread);
        //判断是否为期望线程
        if (currentNum == nextThreadNum) {
            for (int i = 0; i < printOnce; i++) {
                System.out.println("当前线程：" + currentThread.getName() + ":" + nowNum++);
                if (nowNum > targetNum) {
                    System.out.println("工作完成");
                    this.wait();
                }
            }
            //期望线程名+1
            nextThreadNum = (++nextThreadNum) % threadCount;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        PrintQueue ps= new PrintQueue(20, 1);
        ps.setThread(new Thread(new RunTest(ps),"王大锤"));
        ps.setThread(new Thread(new RunTest(ps),"张全蛋"));
        ps.setThread(new Thread(new RunTest(ps),"二狗"));
        ps.run();
    }
}